/**
 * Home
 * 2013.12.16
 * kongge@office.weiphone.com
 */

/**
 * ds.buildSlider
 * 同时也处理图片、楼层等延迟加载
 */
;(function(global, document, $){
	var sliderList = [];
	//buildSlider
	ds.buildSlider = function(shell, ops, buildHandler){
		if(!(shell = $(shell)).length){ return; }

		ops = ops || {};
		var
			triggers = shell.find('.triggers a'),
			_ops = {
				duration: 400,
				unitSize: 880,
				imgLoadFlag: null,
				imgLoadHandler: ds.noop,
				onplay: function(inx, prevInx){
					if(ops.imgLoadFlag && !ops.imgLoadFlag[inx]){
						ops.imgLoadHandler.call(this, inx, prevInx);
						ops.imgLoadFlag[inx] = true;
					}

					prevInx > -1 && triggers.eq(prevInx).removeClass('current');
					triggers.eq(inx).addClass('current');
				}
			};
		for(var k in _ops){
			if(typeof ops[k] === 'undefined'){
				ops[k] = _ops[k];
			}
		}
		if(!ops.shell){
			ops.shell = shell.find('ul').eq(0);
			if(typeof ops.length !== 'number'){
				ops.length = ops.shell.find('li').length;
			}
		}

		var timer, slider = new (buildHandler || Slider)(ops);
		shell.delegate('a.prev,a.next', 'click', function(e){
			e.preventDefault();

			clearTimeout(timer);
			slider[this.className.indexOf('next')>-1 ? 'next' : 'prev']();
		})
			.hover(function(){
				slider.mouseEnter = true;
				slider.stopAuto();
			}, function(){
				slider.mouseEnter = false;
				slider.autoPlay();
			});
		triggers.bind('click', function(e){
			e.preventDefault();
		})
			.hover(function(){
				clearTimeout(timer);
				var self = this;
				timer = setTimeout(function(){
					slider.play(triggers.index(self));
				}, 160);
			}, function(){
				clearTimeout(timer);
			});

		sliderList.push(slider);
		slider.shellWrap = shell;

		//Fix IE6 hover
		if(ds.isIE6){
			var prevAndNext = shell.find('a.prev,a.next');
			shell.hover(function(){
				prevAndNext.show();
			}, function(){
				prevAndNext.hide();
			});
		}
		return slider;
	};

	//floors
	var floors = [];
	$(function(){
		$('div.one_floor').each(function(i){
			floors[i] = $(this);
			floors[i].listMain = floors[i].find('div.list_main').eq(0);
		});
	});

	//scroll
	var
		scrollTimer,
		view = $(global),
		checkScroll = function(){
			var
				viewHeight = view.height(),
				scrollTop = view.scrollTop();
			//checkSlider in viewport
			$.each(sliderList, function(){
				var
					offsetTop = this.shellWrap.offset().top,
					height = this.shellWrap.height();
				if( !this.mouseEnter && ( (offsetTop >= scrollTop && offsetTop <= scrollTop+viewHeight)
					|| (offsetTop+height >= scrollTop && offsetTop+height <= scrollTop+viewHeight) )
				){
					this.autoPlay();
				}
				else{
					this.stopAuto();
				}
			});

			//checkfloor in view viewport
			if(floors.length > 0){
				var vol = 4, slider;
				for(var floor, i=0,len=floors.length; i<len && (floor = floors[i]); i++){
					if(floor.listMain && scrollTop + viewHeight >= floor.offset().top){
						floor.listMain.html(floor.listMain.find('textarea').val());
						floors.splice(i, 1);
						len--;
						i--;

						//Products Score
						getProductsScore(floor.listMain.attr('data-productids'));

						//floor slider
						slider = ds.buildSlider(floor.listMain, {
							auto: false,
							unitSize: 880,
							length: Math.ceil(floor.listMain.find('li').length/vol),
							imgLoadFlag: [],
							imgLoadHandler: function(inx){
								inx = inx * vol;
								this.shell.find('li img')
									.slice(inx, inx + vol).attr('src', function(){
										return this.longDesc;
									});
							}
						});
						floor.listMain = null;
						slider.autoPlay();
					}
				}
				slider = null;
			}
		},
		scrollHandler = function(){
			clearTimeout(scrollTimer);
			scrollTimer = setTimeout(checkScroll, 128);
		};
	view.bind('scroll resize', scrollHandler);
	scrollHandler();
})(window, document, jQuery);

//Banner
jQuery(function($){
	var baseUrl = window.baseJSUrl || 'js/';
	ds.loadScript(baseUrl + 'jquery.FadeList.js', function(){
		var slider = ds.buildSlider('#home_banner', {
			delay: 3200,
			imgLoadFlag: [true],
			imgLoadHandler: function(inx){
				var panel = this.items.eq(inx), img = panel.find('img'), url = img.attr('longDesc');

				panel.css('backgroundImage', 'url('+ url +')');
				img.attr('src', url);
			}
		}, window.FadeList);
	});
});

//精品推荐 & 品牌首发 & 畅销排行 & 最新单品
jQuery(function($){
	//show product detail
	if(!ds.transitionSupport){
		var offset = 78;
		$('.home_tops').delegate('li', 'mouseenter', function(){
			var wrap = $('.props_wrap', this);
			if(!this.fixedMarginTop){
				this.fixedMarginTop = 1;
				wrap.css('marginTop', 0);
			}
			wrap.stop().animate({marginTop:-offset}, 320);
		})
			.delegate('li', 'mouseleave', function(){
				var wrap = $('.props_wrap', this);
				wrap.stop().animate({marginTop:0}, 320);
			});
	}

	//本周热销,精品推荐,新品上市
	function renderHTML(target){
		if(!target.data('initHTML')){
			target.html(target.find('textarea').val());
			target.data('initHTML', true);

			//评分
			getProductsScore(target.attr('data-productids'));
		}
	}
	$('#home_tops .title').tabs({
		delay: 240,
		onselect: function(target){
			if(target.data('tabs_inited')){ return; }
			target.data('tabs_inited', true);

			var subTabPanel = target.find('.order');
			if(subTabPanel.length){
				subTabPanel.tabs({
					delay: 240,
					onselect: renderHTML
				});
			}
			else{
				renderHTML(target);
			}
		}
	});

	//品牌首发
	ds.buildSlider('.home_tops_slider:eq(0)', {
		auto: false,
		unitSize: 260,
		duration: 320,
		imgLoadFlag: [],
		imgLoadHandler: function(inx){
			var img = this.shell.find('li img').eq(inx)
			img.attr('src', img.attr('longDesc'));
		}
	});

	//热门晒单
	var shareOrderShell = $('#home_shareorder .inner');
	ds.buildSlider(shareOrderShell, {
		auto: false,
		unitSize: 1197,
		duration: 400,
		imgLoadFlag: [],
		length: Math.ceil(shareOrderShell.find('li').length/3),
		imgLoadHandler: function(inx){
			var img = this.shell.find('li img').eq(inx)
			img.attr('src', img.attr('longDesc'));
		}
	});
});

/**
 * 页面评分相关
 * @deps getProductsScoreUrl
 * @deps homeProductWhitoutFloorIds
 */
;(function(global, document, $){
	//getProductsScore
	var getProductsScore = window.getProductsScore = function(productIds, url, callback){
		if(!productIds){ return; }
		var getScoreUrl = url || window.getProductsScoreUrl || '/productcomment/comment/getProductScore/';

		$.ajax({
			//type: 'post',
			cache: false,
			dataType: 'json',
			url: getScoreUrl,
			data: {ids: productIds},
			success: callback || function(scoreList){
				if(scoreList && scoreList.length > 0){
					var id, score, count, title, scoreHTML, starElem, floorStar;
					//优化大数组处理，每次只处理 8 个
					var i=scoreList.length;
					(function(){
						for(var c=0; c<8 && --i>=0; c++){
							id = scoreList[i].product_id;
							score = parseFloat(scoreList[i].score) || 0;
							count = ~~scoreList[i].countN;
							title = score + '分，' + count + '人评分';
							scoreHTML = '<em style="width:' + (10 * score) + '%"></em>';
							if((starElem = $('#star_' + id)).length && !starElem.data('setScore')){
								starElem.attr('title', title).html(scoreHTML);
								starElem.data('setScore', true);
							}
							if((floorStar = $('#commented_' + id)).length && !floorStar.data('setScore')){
								if(count > 0){
									scoreHTML = '<span>(' + count + ')</span>' + scoreHTML;
								}
								floorStar.attr('title', title).html(scoreHTML);
								floorStar.data('setScore', true);
							}
						}
						if(i >= 0){
							setTimeout(arguments.callee, 100);
						}
					})();
				}
			}
		});
	};

	//Home Product scores Whitout Floors
	$(function(){
		getProductsScore(window.homeProductWhitoutFloorIds);
	});
})(window, document, jQuery);

/**
 * 首页顶部广告
 * 2013.06.05
 * kongge@office.weiphone.com
 */
jQuery(function($){
	var ops, shell = $('#wea_d_topbar').hide();
	if(!shell.length){ return; }
	try{
		ops = $.parseJSON(shell.attr('data-ops'));
	}
	catch(_){}
	if(ops && ops.src){
		ops = $.extend({
			target: '_blank',
			href: 'http://fengbuy.com',
			//src: 'images/wea_d_1186_156.jpg',
			title: '威锋商城',
			backgroundColor: '#FFF',
			height: 156,
			width: 1186,
			allowClose: true,
			delay: 10, //自动关闭延时，单位 秒，0 - 不自动关闭
			once: true //是否只显示一次，如果是关闭后记录cookie
		}, ops);
		if(ops.once && ops.href === ds.getCookie('wea_d_topbar')){
			return;
		}

		var
			img = new Image(),
			tmpl = '<div class="inner"><a href="<%=href%>" target="<%=target%>"><img src="<%=src%>" height="<%=height%>" width="<%=width%>" alt="<%=title%>" /></a></div><%if(!!allowClose){%><a href="javascript:;" class="close" title="关闭"><span>×</span></a><%}%>',
			closeTopbarAD = function(){
				shell.remove();

				if(ops.once){
					ds.setCookie('wea_d_topbar', ops.href, 7);
				}
			};

		img.onload = function(){
			img.onload = null;

			shell.html(ds.tmpl(tmpl, ops));
			shell.delegate('a.close', 'click', function(e){
				e.preventDefault();
				closeTopbarAD();
			});
			shell.stop().css({
				display: 'block',
				backgroundColor: ops.backgroundColor,
				height: 0
			})
				.animate({height: ops.height}, 600, function(){
					ds.setCookie('wea_d_topbar', '');
					if(~~ops.delay > 0){
						setTimeout(closeTopbarAD, ~~ops.delay * 1000);
					}
				});
		};
		img.src = ops.src;
	}
});

//wea_d_1186_100
jQuery(function($){
	var baseUrl = window.baseJSUrl || 'js/';

	var shell = $('#wea_d_1186_100');
	if(shell.find('li').length <= 1){
		var img = shell.find('img');
		if(img.length && img.attr('longDesc')){
			img.attr('src', img.attr('longDesc'));
		}
		return shell.find('.controller').hide();
	}

	ds.loadScript(baseUrl + 'jquery.FadeList.js', function(){
		var slider = ds.buildSlider('#wea_d_1186_100', {
			delay: 12000,
			imgLoadFlag: [],
			imgLoadHandler: function(inx){
				var panel = this.items.eq(inx), img = panel.find('img');

				img.attr('src', img.attr('longDesc'));
			}
		}, window.FadeList);
	});
});

//团购
/*
 jQuery(function($){
 var
 playing = false,
 shell = $('#home_tuan'),
 panel = shell.find('.tuan_main'),
 placeImg = baseJSUrl + '../images/place.png',
 tmpl = '<div class="list"><ul><% for(var i=0,len=items.length; i<len; i++){ %><li><a href="<%=items[i].href%>" target="_blank" class="pic"><img src="<%=(i>0?"'+ placeImg +'":items[i].img)%>" longdesc="<%=items[i].img%>" height="288" width="240" alt="<%=items[i].title%>" /></a></li><% } %></ul></div><div class="controller"><div class="triggers"><% for(i=0; i<len; i++){ %><a href="javascript:;" class="<%=(i==0?"current":"")%>"><%=(i+1)%></a><% } %></div></div>';

 function initTuan(items){
 var html = ds.tmpl(tmpl, {items:items});
 panel.html(html);

 var
 currInx,
 buyBtn = shell.find('.buy_btn a'),
 slider = ds.buildSlider(panel, {
 length: items.length,
 unitSize: 240,
 delay: 16000,
 imgLoadFlag: [true],
 imgLoadHandler: function(inx, prevInx){
 var imgs = this.shell.find('li img').eq(inx);
 imgs.attr('src', imgs.attr('longDesc'));
 }
 }),
 ops = slider.ops,
 _onplay = ops.onplay;
 ops.onplay = function(inx, prevInx){
 _onplay.apply(this, arguments);

 currInx = inx;
 buyBtn.attr('href', items[inx].href);
 if(items[inx].timeout <= 0){
 clearCounter();
 }
 };

 //Counter
 var
 timer,
 prevDaysStr = '00',
 prevTimerStr = '000000',
 timerPanel = shell.find('.timer').eq(0),
 timerNumShells = timerPanel.find('em.n0'),
 daysPanel = shell.find('.timer_days').eq(0),
 daysNumShells = daysPanel.find('em.n0');
 function clearCounter(){
 timerPanel.show();
 daysPanel.hide();
 for(var i=timerNumShells.length-1; i>=0; --i){
 if(prevTimerStr.charAt(i) !== '0'){
 playNum(timerNumShells, i, 0, 48);
 }
 }
 prevTimerStr = '000000';
 }
 var maxTimeout = 3 * 24 * 3600000; //超过显示天数
 $.each(items, function(inx, item){
 item.timer = ds.startTimeout(item.timeout, function(queue, c){
 if(inx !== currInx || c % 2 !== 0){ return; }
 item.timeout = queue.remaining;

 var tmpStr;
 if(item.timeout <= maxTimeout){
 timerPanel.show();
 daysPanel.hide();

 tmpStr = getTimeStr(queue.remaining, '');
 if(tmpStr !== prevTimerStr){
 timerNumShells.each(function(i){
 if(tmpStr.charAt(i) !== prevTimerStr.charAt(i)){
 playNum(timerNumShells, i, ~~tmpStr.charAt(i), 48);
 }
 });
 prevTimerStr = tmpStr;
 }
 }
 else{
 timerPanel.hide();
 daysPanel.show();

 tmpStr = Math.ceil(queue.remaining/(24*3600000));
 tmpStr = tmpStr < 10 ? '0'+tmpStr : ''+tmpStr;
 if(tmpStr !== prevDaysStr){
 daysNumShells.each(function(i){
 if(tmpStr.charAt(i) !== prevDaysStr.charAt(i)){
 playNum(daysNumShells, i, ~~tmpStr.charAt(i), 48);
 }
 });
 prevDaysStr = tmpStr;
 }
 }


 }, function(){
 item.timeout = 0;
 clearCounter();
 });
 });
 }

 if(window.homeTuanDataUrl){
 $.ajax({
 cahce: false,
 dataType: 'json',
 url: homeTuanDataUrl,
 success: function(data){
 if(data && data.success){
 initTuan(data.dataList);
 }
 }
 });
 }

 //倒计时
 function getTimeStr(ms, split){
 var
 s = ms / 1000,
 h = ~~(s / 3600),
 m = ~~((s - h*3600) / 60);
 s = ~~(s - (h*3600 + m*60));

 var arr = [h<10 ? '0'+h : h, m<10 ? '0'+m : m, s<10 ? '0'+s : s];
 return arr.join(split === void 0 ? ':' : split);
 }

 function getPos(num, frameInx, cInx){
 var
 x = 0,
 y = -38 * (6 * num + frameInx),
 maxNum = [9, 9, 5, 9, 5, 9][cInx];
 if(num === 5 && num === maxNum){
 x = -19;
 }
 return [x, 'px ', y, 'px'].join('');
 }
 function playNum(numShells, inx, toNum, speed){
 var
 elem = numShells[inx % numShells.length],
 style = elem.style,
 c = 0;
 function fx(){
 style.backgroundPosition = getPos(toNum, c++, inx);
 if(c >= 6){
 return clearInterval(elem.timer);
 }
 }
 elem.timer && clearInterval(elem.timer);
 elem.timer = setInterval(fx, speed || 20);
 }
 });
 */
/**
 * 倒计时
 * 步长 100ms
 * 2013.05.27
 * kongge@office.weiphone.com
 */
ds.mix((function(){
	var timer, hasTimer = false, c = 0, queueList = [];
	function checkQueue(){
		timer = setTimeout(checkQueue, 100);
		if(!hasTimer){
			hasTimer = true;
			return;
		}

		c++;
		var queue, elapsed, tMark = +new Date();
		for(var i=0,len=queueList.length; i<len && (queue = queueList[i]); i++){
			elapsed = tMark - queue.startStamp;
			queue.remaining = queue.duration - elapsed;
			if(queue.remaining <= 0){
				len--;
				queueList.splice(i--, 1);
				queue.ondone.call(null, queue, c);
			}
			else{
				queue.onstep.call(null, queue, c);
			}
		}
		if(queueList.length <= 0){
			clearTimeout(timer);
			hasTimer = false;
		}
	}
	return {
		startTimeout: function(ms, onstep, ondone){
			var id = queueList.length + 1;
			queueList.push({
				id: id,
				duration: ~~ms,
				remaining: ~~ms,
				startStamp: +new Date(),
				onstep: onstep || this.noop,
				ondone: ondone || this.noop
			});
			checkQueue();
			return id;
		},
		stopTimeout: function(id){
			for(var i=0,len=queueList.length; i<len; i++){
				if(id === queueList[i].id){
					return queueList.splice(i, 1);
				}
			}
			return {};
		}
	};
})());

//畅销排行
jQuery(function($){
	var shell = $('#rank_slider .inner');
	shell.delegate('li', 'mouseenter', function(){
		shell.find('li').removeClass('current');
		this.className = 'current';
	});
});

//左侧Slider展开操作
jQuery(function($){
	$('.sliderbar .slider').delegate('.extend a', 'click', function(e){
		e.preventDefault();

		var extnd = this.parentNode,
			shell = $(extnd.parentNode).find('.inner'),
			maxHeight = shell.find('ul').height();
		shell.animate({height: maxHeight}, 240);
		extnd.className += ' hide';
	});
});

//二级栏目
jQuery(function($){
	var shell = $('#cat_slider');
	if(!shell.length){ return;}

	shell.find('.pro_sublist').each(function(i){
		var self = $(this);
		self.data('maxHeight', self.height()).css('overflow', 'hidden');
		if(this.parentNode.className.indexOf('current') < 0){
			self.css('height', 0);
		}
	});
	shell.delegate('a.trigger', 'click', function(e){
		e.preventDefault();

		var
			isExtended = this.className.indexOf('open') > -1,
			panel = $('.pro_sublist', this.parentNode.parentNode);
		panel.stop().show().animate({
			height: isExtended ? 0 : panel.data('maxHeight'),
			opacity: isExtended ? 0 : 1
		}, 200, function(){
			if(isExtended){
				panel.hide();
			}
		});
		this.className = isExtended ? 'trigger' : 'trigger open';
	});
});

function showInfoTip(content, type, onhide){
	var icons = {success:'success.png', info: 'info.png'};
	var icon = icons[type] || 'error.png';
	return ds.dialog({
		title: '消息提示',
		content: content,
		onhide: onhide,
		onyes: true,
		icon: icon,
		timeout: 3,
		width: 200
	});
}